package com.vca.admin.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vca.common.config.VcaConfig;
import com.vca.common.constants.Constants;
import com.vca.common.exception.VcaException;
import com.vca.common.model.course.CourseScheduling;
import com.vca.common.model.invoice.InvoiceRecord;
import com.vca.common.model.order.StoreOrder;
import com.vca.common.model.user.User;
import com.vca.common.request.CardPageRequest;
import com.vca.common.request.StoreDateRangeSqlPram;
import com.vca.common.request.UserSearchRequest;
import com.vca.common.result.CommonResult;
import com.vca.common.utils.DateUtil;
import com.vca.common.utils.NumberToCnUtil;
import com.vca.common.utils.ExportUtil;
import com.vca.common.utils.VcaUtil;
import com.vca.common.vo.DetailClientVo;
import com.vca.common.vo.dateLimitUtilVo;
import com.vca.service.service.ExportService;
import com.vca.service.service.InvoiceRecordService;
import com.vca.service.service.StoreOrderService;
import com.vca.service.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Li
 * @description 导出Excel控制器
 * @date 2023-02-16 13:52
 */

@RestController
@RequestMapping("api/admin/excel")
@Api(tags = "导出&导入管理")
@Validated
@Slf4j
public class ExcelController {


    @Autowired
    private ExportService exportService;

    @Autowired
    private VcaConfig vcaConfig;


    @PreAuthorize("hasAuthority('admin:excel:courses:scheduling')")
    @GetMapping("/export/course/scheduling")
    @ApiOperation("课程排期导出")
    public CommonResult<HashMap<String, String>> exportCourse(@RequestParam(value = "date") String date) {
        HashMap<String, String> map = new HashMap<>();
        String newFileName = exportService.courserSchedulingExport(date);
        map.put("url", newFileName);
        return CommonResult.success(map);
    }

    @PreAuthorize("hasAuthority('admin:excel:courses:exportExcelCourseById')")
    @GetMapping("/export/course/exportExcelCourseById")
    @ApiOperation("课程排期导出ExcelById")
    public CommonResult<HashMap<String, String>> exportExcelCourseById(@RequestParam(value = "id") String id) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        String newFileName = exportService.exportExcelCourseSchedulingById(id);
        map.put("url", newFileName);
        return CommonResult.success(map);
    }

    @PreAuthorize("hasAuthority('admin:excel:talk:exportExcelTalkById')")
    @GetMapping("/export/talk/exportExcelTalkById")
    @ApiOperation("讲座排期导出ExcelById")
    public CommonResult<HashMap<String, String>> exportExcelTalkById(@RequestParam(value = "id") String id) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        String newFileName = exportService.exportExcelTalkSchedulingById(id);
        map.put("url", newFileName);
        return CommonResult.success(map);
    }

    @PreAuthorize("hasAuthority('admin:excel:exhibition:exportExcelExhibitionById')")
    @GetMapping("/export/exhibition/exportExcelExhibitionById")
    @ApiOperation("展览排期导出ExcelById")
    public CommonResult<HashMap<String, String>> exportExcelExhibitionById(@RequestParam(value = "id") String id) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        String newFileName = exportService.exportExcelExhibitionSchedulingById(id);
        map.put("url", newFileName);
        return CommonResult.success(map);
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * @param dateLimit
     * @param response
     * @return {@link CommonResult}<{@link Map}<{@link String} ,{@link String}>>
     * @description 导出用户详细报表
     * @author Li
     * @date 2023/2/24 14:30
     */
    @PreAuthorize("hasAuthority('admin:excel:reportFinance')")
    @ApiOperation("导出用户详细报表")
    @GetMapping("/detailClient")
    public CommonResult<Map<String, String>> detailClient(@RequestParam String dateLimit, HttpServletResponse response) {
        if (ObjectUtil.isEmpty(dateLimit)) {
            throw new VcaException("请选择日期");
        }
        //excel文件名
        String fileName = "detailByClient" + System.currentTimeMillis() + ".xlsx";
        Map<String, String> map = new HashMap<>();
        /*map.put("fileName", exportService.detailClient(dateLimit, fileName));
        log.info("" + map);
        return CommonResult.success(map);*/
        String s = null;
        try {
            s = exportService.testDetailClient(dateLimit, fileName,response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        String s = exportService.detailClient(dateLimit, fileName);
        map.put("fileName", s);

        return CommonResult.success(map);



//        HSSFWorkbook wb = exportService.detailClient(dateLimit, fileName);
//        //响应到客户端
//        try {
//            this.setResponseHeader(response, fileName);
//            OutputStream os = response.getOutputStream();
//            wb.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return CommonResult.success();
    }

    /**
     * @param dateLimit
     * @param response
     * @return {@link CommonResult}<{@link Map}<{@link String} ,{@link String}>>
     * @description 每日汇总报表
     * @author Li
     * @date 2023/2/23 14:37
     */
    @PreAuthorize("hasAuthority('admin:excel:reportFinance')")
    @ApiOperation("每日汇总报表")
    @GetMapping("/summaryDay")
    public CommonResult<Map<String, String>> summaryDay(String dateLimit, HttpServletResponse response) {
        if (ObjectUtil.isEmpty(dateLimit)) {
            throw new VcaException("请选择日期");
        }
        //excel文件名
        String fileName = "summaryByDay" + System.currentTimeMillis() + ".xls";
        Map<String, String> map = new HashMap<>();
        map.put("fileName", exportService.summaryDay(dateLimit, fileName));
        return CommonResult.success(map);
//        HSSFWorkbook wb = exportService.summaryDay(dateLimit, fileName);
//        //响应到客户端
//        try {
//            this.setResponseHeader(response, fileName);
//            OutputStream os = response.getOutputStream();
//            wb.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
    * @description  礼品卡报表
    * @param request
    * @param response
    * @author Li
    * @date 2023/9/4 14:04
    * @return {@link CommonResult}<{@link Map}<{@link String},{@link String}>>
    */
    //@PreAuthorize("hasAuthority('admin:excel:reportFinance')")
    @ApiOperation("礼品卡报表")
    @PostMapping("/cardStatement")
    public CommonResult<Map<String, String>> cardStatement(@RequestBody CardPageRequest request, HttpServletResponse response) {
        //excel文件名
        String fileName = "礼品卡报表" + System.currentTimeMillis() + ".xls";
        Map<String, String> map = new HashMap<>();
        map.put("fileName", exportService.cardStatement(request, fileName));
        return CommonResult.success(map);
//        HSSFWorkbook wb = exportService.summaryDay(dateLimit, fileName);
//        //响应到客户端
//        try {
//            this.setResponseHeader(response, fileName);
//            OutputStream os = response.getOutputStream();
//            wb.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    //@PreAuthorize("hasAuthority('admin:excel:reportFinance')")
    @ApiOperation("导出序列号")
    @PostMapping("/exportCdKey")
    public CommonResult<Map<String, String>> exportCdKey(@RequestBody CardPageRequest request, HttpServletResponse response) {
        //excel文件名
        String fileName = "序列号" + System.currentTimeMillis() + ".xls";
        Map<String, String> map = new HashMap<>();
        map.put("fileName", exportService.exportCdKey(request, fileName));
        return CommonResult.success(map);
//        HSSFWorkbook wb = exportService.summaryDay(dateLimit, fileName);
//        //响应到客户端
//        try {
//            this.setResponseHeader(response, fileName);
//            OutputStream os = response.getOutputStream();
//            wb.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
